﻿#include "business.h"

using namespace std;
using namespace uv;

std::string serverip;
int call_time = 0;
bool is_exist = false;
TCPClient gClients;
static ClientType BACKEND_TYPE = NULL;
static struct CMD_Handler * _handler;
static int _count;

void CloseCB(int clientid, void* userdata)
{
    fprintf(stdout, "cliend %d close\n", clientid);
    TCPClient* client = (TCPClient*)userdata;
    client->Close();
}
void OnPacket(const NetPacket& packet, const unsigned char* buf, TCPClient* client);
void ReadCB(const NetPacket& packet, const unsigned char* buf, void* userdata)
{
    TCPClient* client = (TCPClient*)userdata;
    OnPacket(packet,buf,client);
}

void register_backend(ClientType _backend_type)
{
    struct RegisterBusinessHead head;
    head.type = (ClientType)_backend_type;
    head.cmd_count = _count;

    StreamBuffer body_str;
    body_str.append((unsigned char*)&head,sizeof(head));
    for(int i=0;i<_count;i++)
    {
        RegisterBusinessBody body;
        body.cmd = _handler[i].cmd;
        body_str.append((unsigned char*)&body,sizeof(body));
    }
    NetPacket packet;
    packet.cmd = CMD_REGISTER_BACKEND;
    //packet.datalen = body_str.length();

    StreamBuffer str = PacketData(packet, (const unsigned char*)body_str.c_str(),body_str.length());

#ifdef DEBUG
    printf("+++++%d+++\n<",str.length());
    for(int i=0;i<str.length();i++)
    {
        printf("%d,",str[i]);
    }
    printf(">\n-----\n");
#endif
    if (gClients.Send(str.c_str(), str.length()) <= 0) {
        LOGE("(%p)send error.%s\n",&gClients, gClients.GetLastErrMsg());
    } else {
        LOGD("register done");
    }
}

ClientType init_business(struct CMD_Handler ** _handler, int *_count);

int main(int argc, char** argv)
{
    if (argc != 2) {
        fprintf(stdout, "usage: %s server_ip_address\neg.%s 192.168.1.1\n", argv[0], argv[0]);
        return 0;
    }
    //DeclareDumpFile();
    serverip = argv[1];

    //const int clientsize = std::stoi(argv[2]);
    //const int clientsize = atoi(argv[2]);
	BACKEND_TYPE = init_business(&_handler,&_count);
    TCPClient::StartLog("log/");

    {
        gClients.SetRecvCB(ReadCB,&gClients);
        gClients.SetClosedCB(CloseCB,&gClients);
        if (!gClients.Connect(serverip.c_str(), 12345)) {
            LOGE("connect error:%s\n", gClients.GetLastErrMsg());
        } else {
            LOGD("client(%p) connect succeed.\n",&gClients);
            register_backend(BACKEND_TYPE);
        }
    }
    while (!is_exist) {
        sleep(10);
    }
    return 0;
}
